#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include "../thread-pack/LockGuard.hpp"
/**************************************
 *         利用互斥和同步模拟优化抢票功能(先解锁，再去唤醒线程)
 *
 **************************************/
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int tickets = 10000;

void *ThreadRountinue(void *args)
{
    const char *name = static_cast<const char *>(args);
    while (true)
    {
        LockGuard lockguard(&mutex);
        if (tickets > 0)
        {
            usleep(1000);
            std::cout << name << "get a ticket,当前" << tickets << std::endl;
            --tickets;
        }
        else
        {
            std::cout << "没票了,-" << name << std::endl;
            //等待
            pthread_cond_wait(&condition,&mutex);
        }
    }
    return nullptr;
}

int main()
{

    pthread_t t1, t2, t3;
    pthread_create(&t1, nullptr, ThreadRountinue, (void *)"thread-1");
    pthread_create(&t2, nullptr, ThreadRountinue, (void *)"thread-2");
    pthread_create(&t3, nullptr, ThreadRountinue, (void *)"thread-3");

    sleep(5);
    // 没有票了，放票
    int cnt=5;
    while(cnt--){
        std::cout<<"我要准备放票了!!!"<<std::endl;
        sleep(3);
        {
            LockGuard lockguard(&mutex);
            tickets+=1000;
        }
            pthread_cond_signal(&condition);//在唤醒前释放锁吗？//先解锁，再唤醒
        
    }
    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);

    return 0;
}